package com.sunxy.bluetoothdemo

import android.text.TextUtils
import android.util.Log
import com.sunxy.bluetoothdemo.bean.BlueDeviceBean
import com.sunxy.bluetoothdemo.net.InteractorManager
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.TimeUnit


/**
 *
 *
 * @author: sunxy11
 * @email: sunxy11@iflytek.com
 * @date: 2022/11/10
 */
class DataModule(private val adapter: ItemAdapter) {

    private val beanMap by lazy {
        ConcurrentHashMap<String, BlueDeviceBean>()
    }

    private val beanList by lazy { mutableListOf<BlueDeviceBean>() }

    init {
        beanMap.values.forEach {
            if (it.status == 1) it.status = 0
            if (!beanList.contains(it)) beanList.add(it)
        }
        //        adapter.click = { upload(it) }
        Observable.interval(5, 5, TimeUnit.SECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(AndroidSchedulers.mainThread())
            .subscribe({
                    upload()
            },{

            },{

            })
    }

    fun start() {
        adapter.setList(beanList)
        adapter.notifyDataSetChanged()
    }

    fun addBean(bean: BlueDeviceBean) {
        val key = bean.bluetoothAddress
        if (TextUtils.isEmpty(key)) {
            return
        }
        beanMap[key] = bean

        beanList.find { it.bluetoothAddress == bean.bluetoothAddress }?.let { beanList.remove(it) }
        beanList.add(0, bean)

        adapter.notifyDataSetChanged()

        saveBean()

    }

    private fun upload() {
        val uploadBean = mutableListOf<BlueDeviceBean>()
        uploadBean.addAll(beanMap.values)
        if (uploadBean.size == 0) return

        beanMap.clear()
        beanList.clear()
        adapter.notifyDataSetChanged()

        InteractorManager.mainInteractor.upload(uploadBean)
    }

    private fun saveBean() {
//        KvUtils.getKv().putString("data", GsonUtils.getGson().toJson(beanMap))
    }

}